import fs from 'fs';

import * as logger from 'vx/logger.js';
import { packageNames } from 'vx/packageNames.js';
import vxPath from 'vx/vxPath.js';

export default function genNpmIgnore(): void {
  logger.info('Generating .npmignore files...');

  packageNames.list.forEach(packageName => {
    const npmIgnorePath = vxPath.packageNpmIgnore(packageName);

    let existingContent = template;

    if (fs.existsSync(npmIgnorePath)) {
      existingContent = fs.readFileSync(npmIgnorePath, 'utf8');
    }

    const deconstructed = existingContent.split(/(#.*)/g).filter(Boolean); // [comment, content, comment, content]

    deconstructed[1] = genAutoSection();

    const newContent = deconstructed.join('');

    if (existingContent === newContent) {
      logger.log(`✅ ${packageName} .npmignore is up to date. Skipping.`);
      return;
    }

    logger.log(`📝 Writing .npmignore file for ${packageName}`);

    fs.writeFileSync(npmIgnorePath, newContent, 'utf8');
  });

  logger.info('👌 Done generating .npmignore files.\n');
}

const template = `# Autogenerated section. Do not edit manually.



# Manual Section. Edit at will.`;

function genAutoSection(): string {
  return `
node_modules
src
!types/
!dist/
tsconfig.json
!*/package.json

`;
}
